const {
	Service
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config();



module.exports = class AuthService extends Service {
	/*
	* 获取用户信息，含字段 authorities、roles详细
	*/
	async getUserDetails(argObj) {
		var _res_user = argObj._res_user;
		var token = argObj.token;
		const { ctx, service } = this;
		const dbJQL = ctx.event.dbJQL;
		const ip = ctx.context.CLIENTIP;
		dbJQL.setUser({
			role: ['admin']
		})
		try {
			var res_user;
			//根据 token查询用户
			if (!_res_user && token) {
				var vt = await verify_token(token);
				if (vt.code !== 0) return false;
				var res_session = await dbJQL.collection("mh-sys-loginsession")
					.where(`key=='${vt.payload.login_session_key}'`)
					.get({
						getOne: true
					});
				if (!res_session.data) return false;
				var userId = res_session.data.loginUserId;
				res_user = await dbJQL.collection("mh-sys-user")
					.where(`_id=='${userId}'`)
					.get({
						getOne: true
					});
			} 
			// 直接传入用户
			else {
				res_user = _res_user
			}
			if(!res_user.data) return false;
			var tenant_id = res_user.data.tenantId;
			var req_user_result = Object.assign({}, res_user.data, {
				userId: res_user.data._id
			});
			// 判断是不是管理员角色
			var isAdmin = false;
			var roleCodes = req_user_result.roleCodes || [];
			var roleCodesData = await dbJQL.collection("mh-sys-role")
				.where(`in(roleCode, ${JSON.stringify(roleCodes)})`)
				.get();
			var rd = roleCodesData.data || [];
			for(var i=0; i<rd.length; i++){
				if(rd[i].isAdmin == 1){
					isAdmin = 1
					break ;
				}
			}
			// Super
			if(req_user_result.tenantId === '0') isAdmin = 1;
			console.log(isAdmin)
			req_user_result.roles = rd;
			if (isAdmin) {
				// 1、管理员
				req_user_result.isAdmin = 1;
				var menus;
				if(tenant_id === '0') {
					// super超级管理员 - 查tenantId=0下的全部menu
					menus = await dbJQL.collection("mh-sys-menu")
						.where(`tenantId == "0" && deleted != 1`)
						.orderBy(`sortNumber`, `asc`)
						.get();
				}else{
					// 普通超级管理员 - 查对应租户下的全部menu
					var _tenant = await dbJQL.collection("mh-sys-tenant")
						.where(`_id == '${tenant_id}'`)
						.get({
							getOne: true,
						});
						
					menus = await dbJQL.collection("mh-sys-menu")
						.where(`menuId in ${JSON.stringify(_tenant.data.menuIds)} && deleted != 1`)
						.orderBy(`sortNumber`, `asc`)
						.get();
					// 租户管理不返回
					menus.data = menus.data.filter(item=>{
						return (item.path||'').indexOf("/tenant") == -1
					})
				}
				req_user_result.authorities = menus.data||[];
			} else {
				// 2、普通用户
				var authoritiesIds = [];
				(rd||[]).forEach(item=>{
					for(var i=0; i<item.menuIds.length; i++){
						var menuId = item.menuIds[i];
						if(!authoritiesIds.includes(menuId)){
							authoritiesIds.push(menuId)
						}
					}
				})
				var menus = await dbJQL.collection("mh-sys-menu")
					.where(`menuId in ${JSON.stringify(authoritiesIds)} && deleted != 1`)
					.orderBy(`sortNumber`, `asc`)
					.get();
				// 租户管理不返回
				menus.data = menus.data.filter(item=>{
					return (item.path||'').indexOf("/tenant") == -1
				})
				req_user_result.authorities = menus.data||[];
			}
			
			return req_user_result;
		} catch (e) {
			uniCloud.logger.error(e)
			return false
		}
	}
	
	
	
};
